package model;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class XMLUtil {

	
	private static XMLUtil instance;

	public static XMLUtil getInstance() {
		instance = instance == null ? new XMLUtil() : instance;		
		
		return instance;
	}

	
	private Map<String, Map<String,String>> parseDocument(Document dom, String contexts){
		//get the root element
		Element docEle = dom.getDocumentElement();

		//TODO precisa dos nomes dos contexto que estao no XML!

		Map<String, Map<String, String>> query = new HashMap<String, Map<String,String>>();
		
		System.out.println("Contexts: " + contexts);
		
		StringTokenizer st = new StringTokenizer(contexts, ";");
		
		
		while (st.hasMoreTokens()){
			String contextName = st.nextToken().trim();			
			
			//get a nodelist of  elements
			NodeList nl = docEle.getElementsByTagName(contextName);
			if(nl != null && nl.getLength() > 0) {
				for(int i = 0 ; i < nl.getLength();i++) {
					//get the temperature element
					Element element1 = (Element)nl.item(i);					
					Map<String, String> contextValue = new HashMap<String, String>();
					contextValue = getContextValue(element1);
					query.put(contextName, contextValue);
				}
			}
		}
		return query;
	}
	
	
	private Map<String, String> getContextValue(Element element1) {
		Map<String, String> valoresDoContexto = new HashMap<String, String>();
		NamedNodeMap map = element1.getAttributes();
		for(int i = 0; i < map.getLength(); i++){
			Node no = map.item(i);
			valoresDoContexto.put(no.getNodeName(), no.getNodeValue());
		}		
		return valoresDoContexto;
	}

	
	//TODO verificar essas exceptions depois! deve ser lancada ou nao?
	private Document parseXmlFile(String fileNameXML){

		Document dom = null;
		//get the factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {

			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();

			//parse using builder to get DOM representation of the XML file
			dom = db.parse(fileNameXML);

		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
		
		return dom;
	}


	public Map<String, Map<String, String>> translate(String xmlFileName, String contexts) {
		
		Document dom = parseXmlFile(xmlFileName);
		Map<String, Map<String, String>> query = parseDocument(dom, contexts);
		
		return query;
	}
		
}
